package com.xiangyang.pos.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.xiangyang.pos.R;
import com.xiangyang.pos.adapter.GetOrderAdapter;
import com.xiangyang.pos.bean.GetOrderDataBean;
import com.xiangyang.pos.bean.HttpBean;
import com.xiangyang.pos.constant.AppConstant;
import com.xiangyang.pos.http.HttpClient;
import com.xiangyang.pos.http.RequestParameters;
import com.xiangyang.pos.logger.Logger;
import com.xiangyang.pos.utils.SharedUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/12/1 0001.
 *
 * 订单出库
 *
 * @author YeDalin
 *
 */

public class GetOrderListActivity extends Activity implements View.OnClickListener {


    private ImageView ivGoBack;
    private ImageView ivOrderScan;
    private EditText etInputCode;
    private TextView tvSureCode;
    private LinearLayout llOrder;
    private TextView tvOrderNumber;
    private RecyclerView recycler;
    private TextView tvAllMoney;
    private TextView tvTime;
    private TextView tvGetOrder;

    private GetOrderAdapter adapter;
    private List<GetOrderDataBean.GetOrderData> list = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_order_list);
        initView();
        initAdapter();
        showTvGetOrder();
        initClick();
    }

    private void initView() {
        ivGoBack = findViewById(R.id.iv_go_back);
        ivOrderScan = findViewById(R.id.iv_order_scan);
        etInputCode = findViewById(R.id.et_input_code);
        tvSureCode = findViewById(R.id.tv_sure_code);
        llOrder = findViewById(R.id.ll_order);
        tvOrderNumber = findViewById(R.id.tv_order_number);
        recycler = findViewById(R.id.recycler);
        tvAllMoney = findViewById(R.id.tv_all_money);
        tvTime = findViewById(R.id.tv_time);
        tvGetOrder = findViewById(R.id.tv_get_order);

        llOrder.setVisibility(View.GONE);
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(manager);

        adapter = new GetOrderAdapter(list, this);
        recycler.setAdapter(adapter);
    }

    private void initClick() {
        ivGoBack.setOnClickListener(this);
        ivOrderScan.setOnClickListener(this);
        tvSureCode.setOnClickListener(this);
        tvGetOrder.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_go_back:
                finish();
                break;
            case R.id.iv_order_scan:

                new IntentIntegrator(this)
                        .setOrientationLocked(false)
                        .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是CustomActivity
                        .initiateScan(); // 初始化扫描

                break;
            case R.id.tv_sure_code:
                if (etInputCode.getText().toString().length() >= 20) {
                    getOrderHttp(etInputCode.getText().toString());
                }
                break;
            case R.id.tv_get_order:
                getOrderGoodsHttp();
                break;
        }
    }


    //获取订单信息网络访问
    private RequestParameters getOrderData(String orderCode) {
        RequestParameters parameters = new RequestParameters();
        parameters.put("ordercode", orderCode);
        parameters.put("shopid", SharedUtils.getStringPrefs(this, "shopId", ""));
        return parameters;
    }

    private final String GET_ORDER_DATA_URL = AppConstant.POS_URL + "/Placing/An/placing";

    private void getOrderHttp(String orderCode) {

        HttpClient httpClient = new HttpClient();
        httpClient.post(GET_ORDER_DATA_URL, getOrderData(orderCode), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                Logger.e("xxxx", result);

                if (!result.equals("Error")) {

                    Gson gson = new Gson();
                    GetOrderDataBean bean = gson.fromJson(result, GetOrderDataBean.class);

                    if (bean != null) {
                        if (bean.getStatus() == 1) {



                            tvOrderNumber.setText("订单编号：" + bean.getMsg().getOrdercode());
                            tvAllMoney.setText("合计：￥" + bean.getMsg().getFree());
                            tvTime.setText("时间：" + getStrTime(bean.getMsg().getAddtime()));

                            etInputCode.setFocusable(false);
                            etInputCode.setFocusableInTouchMode(false);

                            String id = SharedUtils.getStringPrefs(GetOrderListActivity.this, "shopId", "");

                            for (int i = 0; i < bean.getMsg().getContent().size(); i++) {
                                if (id.equals(bean.getMsg().getContent().get(i).getId() + "")) {
                                    list.addAll(bean.getMsg().getContent().get(i).getShopgoods());
                                }
                            }

                            if(list.size()==0){
                                Toast.makeText(GetOrderListActivity.this, "本店没有该订单的出库商品", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            llOrder.setVisibility(View.VISIBLE);

                            adapter.notifyDataSetChanged();
                            ivOrderScan.setClickable(false);

                            return;

                        }
                    }

                    Toast.makeText(GetOrderListActivity.this, "没有该订单信息或该订单状态错误", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(GetOrderListActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }



    //出库网络访问
    private RequestParameters getGoodsData(String orderCode) {
        RequestParameters parameters = new RequestParameters();
        parameters.put("ordercode", orderCode);
        parameters.put("shopid", SharedUtils.getStringPrefs(this, "shopId", ""));

        String codeArr="";
        for (int i = 0; i < list.size(); i++) {

            codeArr=codeArr+list.get(i).getCode()+",";
        }
        parameters.put("codeArr",codeArr);

        return parameters;
    }

    private final String GET_ORDER_GOODS_URL = AppConstant.POS_URL + "/Placing/An/checkSpacing";

    private void getOrderGoodsHttp() {

        HttpClient httpClient = new HttpClient();
        httpClient.post(GET_ORDER_GOODS_URL, getGoodsData(etInputCode.getText().toString()), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {

                if (!result.equals("Error")) {
                    Gson gson = new Gson();
                    HttpBean bean = gson.fromJson(result, HttpBean.class);
                    if (bean != null) {
                        if (bean.getStatus() == 1) {
                            list.clear();
                            llOrder.setVisibility(View.GONE);
                            etInputCode.setText("");
                            etInputCode.setFocusableInTouchMode(true);
                            ivOrderScan.setClickable(true);
                            tvGetOrder.setVisibility(View.GONE);
                            Toast.makeText(GetOrderListActivity.this, "出库成功", Toast.LENGTH_SHORT).show();
                        }
                    }

                } else {
                    Toast.makeText(GetOrderListActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

//        super.onActivityResult(requestCode, resultCode, data);

        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {

            // ScanResult 为 获取到的字符串
            String scanResult = intentResult.getContents();

            if (scanResult != null) {
                if (scanResult.toString().length() > 20) {//大于20判定为订单编号
                    etInputCode.setText(scanResult);
                    getOrderHttp(scanResult);
                } else if (scanResult.toString().length() > 0) {//大于0小于20判定为商品编码
                    int position = SharedUtils.getIntPrefs(this, "position", -1);

                    Logger.e("xxxx", "" + position);
                    Logger.e("xxxx", scanResult);
                    if (position != -1) {

                        list.get(position).setScanCode(scanResult);
                        adapter.notifyDataSetChanged();
                    }

                }
            }


        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }


    }


    //时间戳转字符串
    public static String getStrTime(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l * 1000));//单位毫秒（注意：l为13位数）
        return timeString;
    }


    //接口回调显示出库按钮
    private void showTvGetOrder() {
        if (adapter != null) {
            adapter.setIsGetOrder(new GetOrderAdapter.IsGetOrder() {
                @Override
                public void okGetOrder() {
                    tvGetOrder.setVisibility(View.VISIBLE);
                }
            });
        }
    }


}
